package com.peng.mybatis_framework.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.peng.mybatis_framework.config.config_entity_property.DynamicConfigSetting;
import com.peng.mybatis_framework.config.config_entity_property.DynamicPropertyPlaceholderConfigurer;

@Configuration
public class PropertyConfiguration {
	
	@Bean(name = "propertyConfig")
	public static DynamicPropertyPlaceholderConfigurer buildPropertyConfigurer(@Value("DEV") String defaultEnvModel,
			@Value("UTF-8") String fileEncoding) {
		
		DynamicPropertyPlaceholderConfigurer propertyConfigurer = new DynamicPropertyPlaceholderConfigurer();
		propertyConfigurer.setDefaultEnvModel(defaultEnvModel);
		propertyConfigurer.setFileEncoding(fileEncoding);
		HashMap<String, DynamicConfigSetting> dynamicConfigSettingMap = new HashMap<>();
		
		//设置开发环境
		dynamicConfigSettingMap.put("TEST", buildDynamicConfigSetting("TEST"));
		//设置测试环境
		dynamicConfigSettingMap.put("DEV", buildDynamicConfigSetting("DEV"));
		//设置生产环境
		dynamicConfigSettingMap.put("OUT_LINE", buildDynamicConfigSetting("OUT_LINE"));
		
		propertyConfigurer.setDynamicConfigSettingMap(dynamicConfigSettingMap);
		return propertyConfigurer;
	}

	private static DynamicConfigSetting buildDynamicConfigSetting(String enMode) {
		DynamicConfigSetting dynamicConfigSetting = new DynamicConfigSetting();
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		ArrayList<Resource> array = new ArrayList<>();
		try {
			//添加各自的配置文件
			Resource[] resources = addEnvFile(enMode,resolver);
			Resource[] applicationPro = resolver.getResources("classpath:application.yml");
			array.addAll(Arrays.asList(resources));
			array.addAll(Arrays.asList(applicationPro));
		} catch (Exception e) {
			throw new RuntimeException("获取资源文件失败");
		}
		dynamicConfigSetting.setPropertyFileLocations(array.toArray(new Resource[array.size()]));
		return dynamicConfigSetting;
	}

	//添加各自环境配置
	private static Resource[] addEnvFile(String enMode,ResourcePatternResolver resolver) throws IOException {
		Resource[] env_resources = null;
		switch (enMode) {
			case "TEST":
				env_resources = resolver.getResources("classpath:env/test-portal.properties");
				break;
			case "DEV":
				env_resources = resolver.getResources("classpath:env/dev-portal.properties");
				break;
			case "OUT_LINE":
				env_resources = resolver.getResources("classpath:env/outline-portal.properties");
				break;
		}
		return env_resources;
	}

}
